package com.wochao.web.app.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.wochao.common.constant.RedisConstant;
import com.wochao.common.exception.ReturnToFrontException;
import com.wochao.common.result.ResultCodeEnum;
import com.wochao.common.utils.JwtUtil;
import com.wochao.common.utils.VerifyCodeUtil;
import com.wochao.model.entity.UserInfo;
import com.wochao.model.enums.BaseStatus;
import com.wochao.web.app.mapper.UserInfoMapper;
import com.wochao.web.app.service.LoginService;
import com.wochao.web.app.service.SmsService;
import com.wochao.web.app.vo.user.LoginVo;
import com.wochao.web.app.vo.user.UserInfoVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.concurrent.TimeUnit;

@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    private SmsService smsService;
    @Autowired
    StringRedisTemplate stringRedisTemplate;
    @Autowired
    private UserInfoMapper userInfoMapper;

    /**
     * 获取短信验证码
     *
     * @param phone
     */
    @Override
    public void getCode(String phone) {

        //判断手机号码是否为空
        if (!StringUtils.hasText(phone)) {
            throw new ReturnToFrontException(ResultCodeEnum.APP_LOGIN_PHONE_EMPTY);
        }
        //检查Redis中是否已存在该手机号码的key
        String key = RedisConstant.APP_LOGIN_PREFIX + phone;
        Boolean hasKey = stringRedisTemplate.hasKey(key);
        if (hasKey) {
            //若存在，则检查其存在的时间
            Long expire = stringRedisTemplate.getExpire(key, TimeUnit.SECONDS);
            if (RedisConstant.APP_LOGIN_CODE_TTL_SEC - expire < RedisConstant.APP_LOGIN_CODE_RESEND_TIME_SEC) {
                //若存在时间不足一分钟，则响应"验证码发送过于频繁"
                throw new ReturnToFrontException(ResultCodeEnum.APP_SEND_SMS_TOO_OFTEN);
            }
        }

        //发送短信，并将验证码存入Redis
        String code = VerifyCodeUtil.getVerifyCode(4);
        smsService.sendCode(phone, code);
        stringRedisTemplate.opsForValue().set(key, code, RedisConstant.APP_LOGIN_CODE_TTL_SEC, TimeUnit.SECONDS);

    }

    /**
     * 登录
     *
     * @param loginVo
     * @return
     */
    @Override
    public String login(LoginVo loginVo) {

        //判断手机号码和验证码是否为空
        if (!StringUtils.hasText(loginVo.getPhone())) {
            throw new ReturnToFrontException(ResultCodeEnum.APP_LOGIN_PHONE_EMPTY);
        }
        if (!StringUtils.hasText(loginVo.getCode())) {
            throw new ReturnToFrontException(ResultCodeEnum.APP_LOGIN_CODE_EMPTY);
        }

        //校验验证码
        String key = RedisConstant.APP_LOGIN_PREFIX + loginVo.getPhone();
        String code = stringRedisTemplate.opsForValue().get(key);

        if (!code.equals(loginVo.getCode())) {
            throw new ReturnToFrontException(ResultCodeEnum.APP_LOGIN_CODE_ERROR);
        }

        //判断用户是否存在
        LambdaQueryWrapper<UserInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserInfo::getPhone, loginVo.getPhone());
        UserInfo userInfo = userInfoMapper.selectOne(queryWrapper);

        if (userInfo == null) {
            //不存在则注册（创建用户）
            userInfo = new UserInfo();
            userInfo.setPhone(loginVo.getPhone());
            userInfo.setStatus(BaseStatus.ENABLE);
            userInfo.setNickname("用户-" + loginVo.getPhone().substring(7));
            userInfoMapper.insert(userInfo);
        }

        //判断用户是否被禁
        if (userInfo.getStatus().equals(BaseStatus.DISABLE)) {
            throw new ReturnToFrontException(ResultCodeEnum.APP_ACCOUNT_DISABLED_ERROR);
        }

        //创建并返回Token
        return JwtUtil.createToken(userInfo.getId(), loginVo.getPhone());

    }

    /**
     * 获取登录用户信息
     *
     * @param userId
     * @return
     */
    @Override
    public UserInfoVo getLoginUserById(Long userId) {
        UserInfo userInfo = userInfoMapper.selectById(userId);
        UserInfoVo userInfoVo = new UserInfoVo(userInfo.getNickname(),userInfo.getAvatarUrl());

        return userInfoVo;
    }
}
